'use strict';

webappApp.directive('upload', function() {
  var setStatus = function (scope, status) {
    var s = status || 'warning',
      bar = s;

    if (angular.equals('error', bar)) {
      bar = 'danger';
    }

    scope.barClass = ['progress', 'progress-' + bar];
    scope.status = 'upload-' + s;
    scope.active = [];
    if (angular.equals('info') && !scope.error) {
      scope.active = ['active', 'progress-striped'];
    }
  };
  return {
    templateUrl: 'tmpl/upload.html',
    scope: {
      file: '=',
      cancel: '='
    },
    restrict: 'E',
    link: function postLink(scope, element, attrs) {
      setStatus(scope, undefined);
      scope.$watch('file.progress', function (progress) {
        if (progress > 0 && progress < 100) {
          setStatus(scope, 'info');
        } else if (progress >= 100) {
          setStatus(scope, 'success');
        } else {
          setStatus(scope, undefined);
        }
      }, true);
      scope.$watch('file.error', function (error) {
        if (error) {
          setStatus(scope, 'error');
        }
      });
    }
  };
});
